package cn.plushine.interceptor;

import cn.plushine.utils.JWTUtils;
import com.alibaba.fastjson.JSONArray;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

/**
 * JWT拦截器，拦截不合法的Token
 */
// 实现SpringMVC提供的HandlerInterceptor接口
public class JWTInterceptor implements HandlerInterceptor {
    //重写处理前的方法
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从请求头中获取token参数
        String token = request.getHeader("token");

        HashMap<String, Object> map = new HashMap<>();
        try {
            DecodedJWT jwt = JWTUtils.verifyToken(token);
            // 放行拦截器
            return true;
        } catch (SignatureVerificationException e) {
            map.put("msg", "签名无效！");
        } catch (TokenExpiredException e) {
            map.put("msg", "token过期！");
        } catch (AlgorithmMismatchException e) {
            map.put("msg", "token算法不一致！");
        } catch (Exception e) {
            map.put("msg", "token无效！");
        }
        map.put("status", false);

        // 异常，将map数据以JSON格式化通过response响应给前台

        // 使用fastjson将map格式强制转换为json格式，JSONArray.toJSONString(map)
        response.setContentType("application/json;charset=UTF8");
        response.getWriter().println(JSONArray.toJSONString(map));
        return false;
    }
}
